package com.ruoyi.system.service.impl;

import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.http.HttpUtils;
import com.ruoyi.system.domain.RyFileCreate;
import com.ruoyi.system.service.IRyFileCreateService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import com.ruoyi.system.mapper.RyFileDownloadHistoryMapper;
import com.ruoyi.system.domain.RyFileDownloadHistory;
import com.ruoyi.system.service.IRyFileDownloadHistoryService;

/**
 * 文件下载记录Service业务层处理
 * 
 * @author ruoyi
 * @date 2025-11-05
 */
@Service
public class RyFileDownloadHistoryServiceImpl implements IRyFileDownloadHistoryService 
{

    private static final Logger LOGGER = LoggerFactory.getLogger(RyFileDownloadHistoryServiceImpl.class);
    @Autowired
    private RyFileDownloadHistoryMapper ryFileDownloadHistoryMapper;
    @Autowired
    private IRyFileCreateService ryFileCreateService;

    /**
     * 查询文件下载记录
     * 
     * @param id 文件下载记录主键
     * @return 文件下载记录
     */
    @Override
    public RyFileDownloadHistory selectRyFileDownloadHistoryById(Long id)
    {
        return ryFileDownloadHistoryMapper.selectRyFileDownloadHistoryById(id);
    }

    /**
     * 查询文件下载记录列表
     * 
     * @param ryFileDownloadHistory 文件下载记录
     * @return 文件下载记录
     */
    @Override
    public List<RyFileDownloadHistory> selectRyFileDownloadHistoryList(RyFileDownloadHistory ryFileDownloadHistory)
    {
        return ryFileDownloadHistoryMapper.selectRyFileDownloadHistoryList(ryFileDownloadHistory);
    }

    /**
     * 新增文件下载记录
     * 
     * @param ryFileDownloadHistory 文件下载记录
     * @return 结果
     */
    @Override
    public int insertRyFileDownloadHistory(RyFileDownloadHistory ryFileDownloadHistory)
    {
        ryFileDownloadHistory.setCreateBy(SecurityUtils.getUserId().toString());
        ryFileDownloadHistory.setCreateTime(DateUtils.getNowDate());
        ryFileDownloadHistory.setUpdateBy(SecurityUtils.getUserId().toString());
        ryFileDownloadHistory.setUpdateTime(DateUtils.getNowDate());
//        RyFileCreate ryFileCreate = ryFileCreateService.selectRyFileCreateById(ryFileDownloadHistory.getFileId());
        ryFileDownloadHistory.setFileName(ryFileDownloadHistory.getFileName());
        List<RyFileDownloadHistory> files = ryFileDownloadHistoryMapper.selectFileDtl(ryFileDownloadHistory);
        if(!files.isEmpty()) {
            JSONObject jsonObject = new JSONObject().fluentPut("fileName", ryFileDownloadHistory.getFileName()).fluentPut("sendSysCode", ryFileDownloadHistory.getSendSysCode()).fluentPut("recvSysCode", ryFileDownloadHistory.getRecvSysCode());
            String res = HttpUtils.sendPost("http://10.14.106.103:8091/get",jsonObject.toJSONString(), MediaType.APPLICATION_JSON_VALUE);
            LOGGER.info("文件下载接口返回:{}",res);
            if (StringUtils.isNotEmpty(res)){
                try{
                    JSONObject reponse = JSON.parseObject(res);
                    ryFileDownloadHistory.setFlag(reponse.getInteger("code").toString());
                    if (reponse.getInteger("code")==200){
                        ryFileDownloadHistory.setMsg("成功");
                    }else {
                        ryFileDownloadHistory.setMsg("失败");
                    }
                    if (StringUtils.isNotEmpty(reponse.getJSONObject("info"))){
                        ryFileDownloadHistory.setInfo(reponse.getJSONObject("info").toJSONString());
                    }
                }catch (Exception e){
                    ryFileDownloadHistory.setMsg("失败");
                }

            }
        } else {
            ryFileDownloadHistory.setMsg("没有该文件，失败");
        }

        ryFileDownloadHistory.setCreateTime(DateUtils.getNowDate());
        return ryFileDownloadHistoryMapper.insertRyFileDownloadHistory(ryFileDownloadHistory);
    }

    /**
     * 修改文件下载记录
     * 
     * @param ryFileDownloadHistory 文件下载记录
     * @return 结果
     */
    @Override
    public int updateRyFileDownloadHistory(RyFileDownloadHistory ryFileDownloadHistory)
    {
        ryFileDownloadHistory.setUpdateBy(SecurityUtils.getUserId().toString());
        ryFileDownloadHistory.setUpdateTime(DateUtils.getNowDate());
        return ryFileDownloadHistoryMapper.updateRyFileDownloadHistory(ryFileDownloadHistory);
    }

    /**
     * 批量删除文件下载记录
     * 
     * @param ids 需要删除的文件下载记录主键
     * @return 结果
     */
    @Override
    public int deleteRyFileDownloadHistoryByIds(Long[] ids)
    {
        return ryFileDownloadHistoryMapper.deleteRyFileDownloadHistoryByIds(ids);
    }

    /**
     * 删除文件下载记录信息
     * 
     * @param id 文件下载记录主键
     * @return 结果
     */
    @Override
    public int deleteRyFileDownloadHistoryById(Long id)
    {
        return ryFileDownloadHistoryMapper.deleteRyFileDownloadHistoryById(id);
    }

    /**
     * 获取指定文件夹下的所有文件路径（不包含子文件夹）
     * @param folderPath 文件夹路径
     * @return 文件路径列表
     */
    public List<String> getFilesInFolder(String folderPath) {
        File folder = new File(folderPath);

        if (!folder.exists() || !folder.isDirectory()) {
            System.err.println("错误：文件夹不存在或不是有效文件夹 - " + folderPath);
            return new ArrayList<>();
        }

        File[] files = folder.listFiles();
        if (files == null) {
            return new ArrayList<>();
        }

        return Arrays.stream(files)
                .filter(File::isFile)
                .map(File::getAbsolutePath)
                .collect(Collectors.toList());
    }
}
